<?php

namespace IDock\Insurance\DAJIA\Request;

use Exception;
use IDock\Insurance\DAJIA\DAJIAEnums;
use IDock\Insurance\DAJIA\Response\CommonResponse;
use IDock\Visitor\Premium\PremiumCoverageVisitor;
use IDock\Visitor\Premium\PremiumInquiryVisitor;

/**
 * 车辆信息和客户信息查询接口
 */
class VehicleAndCustomerInfoConfirmRequest extends AllDAJIARequest
{
    protected $code = 'ODR1008';

    protected $response = CommonResponse::class;

    protected $urlTip = '车辆和客户信息确认';

    /**
     * @var PremiumInquiryVisitor $visitor
     */
    protected $visitor;

    /**
     * @throws Exception
     */
    public function generate(): array
    {
        return [
            'orderNo' => $this->visitor->getExtInfoVisitor()->argc['orderNo'] ?? '',
            'applicantInfo' => $this->getApplicantInfo(),
            'businessInfo' => $this->getBusinessInfo(),
            'insuredInfo' => $this->getInsuredInfo(),
            'vehicleInfo' => $this->getVehicleInfo(),
            'vehicleOwnerInfo' => $this->getOwnerInfo(),
        ];
    }

    /**
     * @throws Exception
     */
    private function getApplicantInfo(): array
    {
        $applicantInfo = $this->visitor->getApplicantVisitor();
        $applicant = [
            "applicantChasalesCertfCde" => "",
            "applicantChasalesCertfCls" => "",
            "applicantChasalesClntMrk" => "",
            "applicantChasalesEmail" => "",
            "applicantChasalesMobile" => "",
            "applicantChasalesNme" => "",
            "applicantNme" => $applicantInfo->name,//姓名
            "applicantPhoneCertfCde" => "",
            "applicantPhoneCertiType" => "",
            "applicantPhoneName" => "",
            "applicantPhoneType" => "",
            "applicantCCertfCde" => $applicantInfo->certificateNo,//证件号码
            "applicantCCertfCls" => DAJIAEnums::$certificateTypeCode[$applicantInfo->certificateTypeCode],//证件类型
            "applicantClntMrk" => DAJIAEnums::$relationTypeCode[$applicantInfo->typeCode],//客户分类
            "applicantProvince" => $applicantInfo->provinceCode,
            "applicantCity" => $applicantInfo->cityCode,
            "applicantCounty" => $applicantInfo->areaCode,
            "applicantSuffixAddr" => $applicantInfo->address,
            "applicantClntAddr" => $applicantInfo->address,
            "applicantZipCde" => $applicantInfo->postcode,//邮编
            "applicantEmail" => $applicantInfo->email,
            "applicantEthnicity" => "",
            "applicantHomeAddr" => "",
            "applicantIssueOrg" => "",
            "applicantMobile" => $applicantInfo->mobile,
            "applicantNote" => "",
            "applicantPayerRel" => "",
            "applicantSex" => "",//性别
            "applicantTBirthday" => "",//出生日期
            "applicantTEffectiveDate" => $applicantInfo->certificateStartDate,//证件有效期
            "applicantTExpiredDate" => $applicantInfo->certificateEndDate,//证件有效期
            "applicantEmPower" => "",
            "applicantCBusiness" => "",
            "applicantCCusRiskLvl" => "",
            "applicantCNation" => "",
            "applicantCProfissionXiq1" => "",
            "applicantCProfissionXiq2" => "",
            "applicantWorkDpt" => "",
            "applicantCCountry" => "",
            "applicantTel" => ""
        ];
        //投保人为个人
        if ($applicant['applicantClntMrk'] == 1) {
            $applicant['applicantSex'] = $this->getGenderByIDCard($applicant['applicantCCertfCde']);
            $applicant['applicantTBirthday'] = $this->getBirthday($applicant['applicantCCertfCde']);
        }
        return $applicant;
    }

    /**
     * 通过身份证获取性别
     * @param $idCard
     * @return string
     * @throws Exception
     */
    private function getGenderByIDCard($idCard): string
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        $gender = intval(substr($idCard, 16, 1)) % 2;
        return $gender ? '3A05001' : '3A05002';
    }

    /**
     * @throws Exception
     */
    private function getBirthday($idCard): string
    {
        if (strlen($idCard) != 18) {
            throw new Exception("身份证位数不合法");
        }
        return substr($idCard, 6, 4) . '-' . substr($idCard, 10, 2) . '-' . substr($idCard, 12, 2);
    }

    public function getBusinessInfo(): array
    {
        $extInfo = $this->visitor->getExtInfoVisitor();
        $busiId = $extInfo->argc['busiId'] ?? '';
        return [
            "busiId" => $busiId,
            "busiOpdpt" => $extInfo->argc['busiOpdpt'] ?? '',
            "busiDptCde" => $extInfo->argc['busiDptCde'] ?? '',
            "busiBrkrCde" => $extInfo->argc['busiBrkrCde'] ?? '',
            "busiAgentNme" => "",
            "busiGrantDptCde" => "",
            "busiGrantDptNme" => "",
            "busiOprCde" => $extInfo->argc['busiOprCde'] ?? '',
            "busiOprNme" => "",
            "busiBsnsTyp" => $extInfo->argc['busiBsnsTyp'] ?? '',
            "busiSlsId" => "",
            "busiSlsCde" => $extInfo->argc['busiSlsCde'] ?? '',
            "busiChaSalesId" => "",
            "busiSlsNme" => "",
            "busiRecommendCde" => $extInfo->argc['busiRecommendCde'] ?? '',
            "busiRecSubChannel" => $extInfo->argc['busiRecSubChannel'] ?? '',
            "busiCoopCde" => "",
            "busiCoopNme" => "",
            "busiRepairFlag" => "0",
            "busiGarageCode" => "",
            "busiGarageName" => "",
            "busiServiceCode" => "",
            "busiChannelSrc" => $extInfo->argc['busiChannelSrc'] ?? '',
            "busiDataSrc" => $extInfo->argc['busiDataSrc'] ?? '',
            "busiDataFlag" => $extInfo->argc['busiDataFlag'] ?? ''
        ];
    }

    /**
     * @throws Exception
     */
    private function getInsuredInfo(): array
    {
        $insuredInfo = $this->visitor->getInsuredVisitor();
        $insured = [
            "insuredPhoneCertfCde" => "",
            "insuredPhoneCertiType" => "",
            "insuredPhoneName" => "",
            "insuredPhoneType" => "",
            "insuredCertfCde" => $insuredInfo->certificateNo,
            "insuredCertfCls" => DAJIAEnums::$certificateTypeCode[$insuredInfo->certificateTypeCode],//证件类型
            "insuredProvince" => $insuredInfo->provinceCode,
            "insuredCity" => $insuredInfo->cityCode,
            "insuredCounty" => $insuredInfo->areaCode,
            "insuredSuffixAddr" => $insuredInfo->address,
            "insuredClntAddr" => $insuredInfo->address,
            "insuredClntMrk" => DAJIAEnums::$relationTypeCode[$insuredInfo->typeCode],//客户分类,
            "insuredEmail" => $insuredInfo->email,
            "insuredHomeAddr" => "",
            "insuredNme" => $insuredInfo->name,
            "insuredEthnicity" => "",
            "insuredIssueOrg" => "",
            "insuredMobile" => $insuredInfo->mobile,
            "insuredResidAddr" => $insuredInfo->address,
            "insuredSex" => '',
            "insuredZipCde" => $insuredInfo->postcode,
            "insuredTBirthday" => "",
            "insuredTEffectiveDate" => $insuredInfo->certificateStartDate,//证件有效期,
            "insuredTExpiredDate" => $insuredInfo->certificateEndDate,//证件有效期
            "insuredBusiness" => "",
            "insuredCusRiskLvl" => "",
            "insuredNation" => "",
            "insuredProfissionXiq1" => "",
            "insuredProfissionXiq2" => "",
            "insuredWorkDpt" => "",
            "insuredCountry" => "",
            "insuredTel" => ""
        ];
        //被保人为个人
        if ($insured['insuredClntMrk'] == 1) {
            $insured['insuredSex'] = $this->getGenderByIDCard($insuredInfo->certificateNo);
            $insured['insuredTBirthday'] = $this->getBirthday($insuredInfo->certificateNo);
        }
        return $insured;
    }

    private function getOwnerInfo()
    {
        $ownerInfo = $this->visitor->getOwnerVisitor();
        $owner = [
            "vehicleOwnerCCertfCde" => $ownerInfo->certificateNo,
            "vehicleOwnerCCertfCls" => DAJIAEnums::$certificateTypeCode[$ownerInfo->certificateTypeCode],//证件类型
            "vehicleOwnerCClntAddr" => $ownerInfo->address,
            "vehicleOwnerCContactTel" => $ownerInfo->mobile,
            "vehicleOwnerCEmail" => $ownerInfo->email,
            "vehicleOwnerCMobile" => $ownerInfo->mobile,
            "vehicleOwnerCOwnerCls" => DAJIAEnums::$relationTypeCode[$ownerInfo->typeCode],//客户分类,
            "vehicleOwnerCOwnerNme" => $ownerInfo->name,
            "vehicleOwnerCZipCde" => $ownerInfo->postcode,
            "vehicleOwnerTBirthday" => "",
            "vehicleOwnerTExpiredDate" => $ownerInfo->certificateEndDate,//证件有效期
            "vehicleOwnerCNation" => "1",//中国
            "vehicleOwnerCSex" => "",
            "vehicleOwnerCWorkdptKind" => "",
            "vehicleOwnerCCountry" => "",
            "vehicleOwnerProvince" => $ownerInfo->provinceCode,
            "vehicleOwnerCity" => $ownerInfo->cityCode,
            "vehicleOwnerCounty" => $ownerInfo->areaCode,
            "vehicleOwnerSuffixAddr" => ""
        ];
        //被保人为个人
        if($owner['vehicleOwnerCOwnerCls'] == 1){
            $owner['vehicleOwnerCSex'] = $this->getGenderByIDcard($ownerInfo->certificateNo);
            $owner['vehicleOwnerTBirthday'] = $this->getBirthday($ownerInfo->certificateNo);
        }
        return $owner;
    }

    /**
     * 获取车辆信息
     * @return array
     * @throws Exception
     */
    private function getVehicleInfo() :array
    {
        $vehicleInfo = $this->visitor->getVehicleVisitor();
        $extInfo = $this->visitor->getExtInfoVisitor();
        $vehicle = [
            "vehicleEngNo" => $vehicleInfo->engineNo,//引擎编号
            "vehicleFrmNo" => $vehicleInfo->vin,//车架号
            "vehicleChgOwnerFlag" => $vehicleInfo->isTransfer,//是否过户
            "vehicleFstRegYmBar" => $vehicleInfo->firstRegisterDate,//初登日期
            "vehicleFuelType" => DAJIAEnums::$energyType[$vehicleInfo->energyTypeCode],
            "vehicleModelCde" => $vehicleInfo->vehicleModelCode,
            "vehiclePlateNo" => $vehicleInfo->licenseNo,
            "vehiclePlateTyp" => '',
            "vehicleRegVhlTyp" => $vehicleInfo->vehicleStyleCode,//交管车辆类型
            "vehicleTfiSpecialMrk" => $vehicleInfo->isCiTransfer,//交强险特殊车标志 1 过户
            "vehicleUsageCde" => "",//家庭自用客车
            "vehicleVhlCertNo" => "",
            "vehicleVhlCertType" => "",
            "vehicleNConsultPurchaseValue" => $vehicleInfo->actualValue,//协商价格
            "vehicleTBuyCarDate" => "",
            "vehicleTTransferDate" => '',
            "vehicleTVhlCertDate" => "",
            "vehicleSpecialRiskFlag" => "0",//特殊风险标识
            "vehicleNPower" => $vehicleInfo->power,
            "vehicleIs4SShop" => "",
            "vehicleCSaleCompany" => "",
            "vehicleSaleAreaCode" => "",
            "vehicleModelEnergyType" => DAJIAEnums::$energyType[$vehicleInfo->energyTypeCode],//交强燃油类型
            "vehicleNPureRange" => $vehicleInfo->pureRange,//纯电续航里程(公里)
            "vehicleTraUsageCde" => "",//交管使用性质
            "vehicleIsQuery" => "1",
            "vehicleEcdemicMrk" => $vehicleInfo->nonlocalCar,//外地车标识
            "vehicleLoanvehicleFlag" => "",
            "vehicleNCurbWt" => round(intval($vehicleInfo->wholeWeight) / 1000, 2),//整备质量
            "vehicleNSeatNum" => $vehicleInfo->vehicleSeat,//座位
            "vehicleNNewPurchaseValue" => $vehicleInfo->vehiclePriceTax,//新车购置价
            "vehicleModelNme" => $vehicleInfo->vehicleName,//车型名称
            "vehicleNTonage" => "",
            "vehicleNDisplacement" => $vehicleInfo->vehicleExhaust,//排量
            "vehicleVhlTyp" => "",//车辆种类
            "vehicleBrandId" => "",
            "vehicleNewMrk" => $vehicleInfo->licenseNo ? 0 : 1,//是否上牌
            "vehicleNewPlate" => intval($vehicleInfo->isNewVehicle),//新车标志
            "vehicleAnswer" => "",
            "vehicleTCertificateDate" => $this->visitor->getVehicleVisitor()->issueDate,//发证日期
            "vehicleInspectionCde" => DAJIAEnums::$carCheckCode[$extInfo->carCheckCode],//验车情况 305005002
            "vehicleInspectTm" => $extInfo->carCheckDate,//验车时间
            "vehicleInspectorNme" => $extInfo->carChecker,//验车人
            "vehicleInspectRec" => "",//验车结果
            "vehicleResvTxt1" => "",//免验原因
            "vehicleResvTxt8" => $vehicleInfo->isCiTransfer,//是否过户,
            "vehicleTransferTm" => $vehicleInfo->transferDate,
            "vehicleDamagedSite" => "",
            "vehicleStyleUniqueId" => "",
            "vehicleIndustryModelCode" => ""
        ];

        if (!empty($vehicleInfo->transferDate)) {
            $vehicle['vehicleTTransferDate'] = $vehicleInfo->transferDate;
        }
        if (!empty($vehicleInfo->licenseNo)) {
            $vehicle['vehiclePlateTyp'] = $vehicleInfo->licenseTypeCode;
        }
        $vehicle['vehicleUsageCde'] = $this->getCIVehicleCode($vehicleInfo->attachNature, $vehicleInfo->carKindCode, $vehicleInfo->causeType);
        $coverageType = $this->getCoverageType($this->visitor->getCoverageVisitorList());
        //单交强险种类型
        $vehicle['vehicleUsageCde'] = $this->checkJqCode($coverageType, $vehicle['vehicleUsageCde']);
        if ($vehicle['vehicleUsageCde'] == '') {
            throw new Exception("不支持该车辆类型");
        }
        $seat = $vehicleInfo->vehicleSeat;
        if ($seat < 6) {
            $vehicle['vehicleVhlTyp'] = DAJIAEnums::$carType['01'];
        } else if ($seat < 10) {
            $vehicle['vehicleVhlTyp'] = DAJIAEnums::$carType['02'];
        } else if ($seat < 20) {
            $vehicle['vehicleVhlTyp'] = DAJIAEnums::$carType['03'];
        } else if ($seat < 36) {
            $vehicle['vehicleVhlTyp'] = DAJIAEnums::$carType['04'];
        } else if ($seat >= 36) {
            $vehicle['vehicleVhlTyp'] = DAJIAEnums::$carType['05'];
        }
        if (empty($vehicle['vehicleInspectionCde'])) {
            throw new Exception("不支持的验车情况");
        }
        //验车情况
        if ($vehicle['vehicleInspectionCde'] == '305005002') {
            //已验
            $vehicle['vehicleInspectTm'] = $extInfo->carCheckDate;//验车时间
            $vehicle['vehicleInspectorNme'] = $extInfo->carChecker ?? '';//验车人
            $vehicle['vehicleInspectRec'] = '382001';//验车结果, 全车完好无损，证车相符，年审合格
        } else if ($vehicle['vehicleInspectionCde'] == '305005003') {
            //免验车
            $vehicle['vehicleResvTxt1'] = DAJIAEnums::$carCheckReasonKind[$extInfo->carCheckReasonKind];
        }

        return $vehicle;
    }

    public function getCIVehicleCode($attachNature, $carKindCode, $causeType): string
    {
        $vehicleUsage = $attachNature . $carKindCode . $causeType;
        switch ($vehicleUsage) {
            case '01100001':
                $code = '374001';//家庭自用
                break;
            case '03100003':
                $code = '374002';//非营业企业客车
                break;
            case '02100002':
                $code = '374003';//非营业机关客车
                break;
            case '01200001':
                $code = '374004';//非营业个人货车
                break;
            case '03200003':
                $code = '374005';//非营业企业货车
                break;
            case '02200002':
                $code = '374006';//非营业机关货车
                break;
            case '01200008':
                $code = '374010';//营业个人.货车
                break;
            case '03200008':
                $code = '374014';//营业企业.货车
                break;
            default:
                $code = '';
                break;
        }
        return $code;
    }

    /**
     * 获取险种类型
     * @param $dataList
     * @return string
     */
    public function getCoverageType($dataList): string
    {
        $coverageList = [];//险种
        /*** @var PremiumCoverageVisitor $coverageVisitor */
        foreach ($dataList as $coverageVisitor) {

            $coverageList[] = $coverageVisitor->coverageCode;
        }
        if (count($coverageList) == 1) {
            if ($coverageList[0] == 'C01001') {
                $coverageType = '1';//单交强
            } else {
                $coverageType = '2';//商业险
            }
        } else {
            if (in_array('C01001', $coverageList)) {
                $coverageType = '3';//交商同保
            } else {
                $coverageType = '2';//商业险
            }
        }
        return $coverageType;
    }

    public function checkJqCode($coverageType, $code)
    {
        if ($coverageType == 1) {
            if ($code == '374001') {
                $code = '364001001';//家庭自用
            } else if ($code == '374003') {
                $code = '364002001';//非营业客车(机关、事业团体)
            } else if ($code == '374002') {
                $code = '364002002';//非营业客车(企业)
            } else if (in_array($code, ['374004', '374005'])) {
                $code = '364004001';//货车(非营业货车)
            } else if (in_array($code, ['374010', '374014'])) {
                $code = '364004002';//货车(营业货车)
            }
        }
        return $code;
    }
}
